﻿/* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 Validity Systems Inc.  All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
*    notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
*    notice, this list of conditions and the following disclaimer in
*    the documentation and/or other materials provided with the
*    distribution.
*
* 3. The end-user documentation included with the redistribution, if
*    any, must include the following acknowlegement:
*       "This product includes software developed by the
*        Validity Systems Inc."
*    Alternately, this acknowlegement may appear in the software itself,
*    if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "#Logger", "CS Logger", and "Validity Systems
*    Inc." must not be used to endorse or promote products derived
*    from this software without prior written permission. For written
*    permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "#Logger"
*    nor may "#Logger" appear in their names without prior written
*    permission of Validity Systems Inc.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED.  IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Validity Systems Inc.
*
*
*/

namespace VS
{
    using System;
    using System.Collections;
    using System.Collections.Generic;
    using System.IO;
    using System.Reflection;
    using System.Threading;

    /// <summary>
    /// Logger levels enum.
    /// </summary>
    public enum LoggerLevels
    {
        /// <summary>
        /// Critical log type.
        /// </summary>
        Critical,

        /// <summary>
        /// Error log type.
        /// </summary>
        Error,

        /// <summary>
        /// Warning log type.
        /// </summary>
        Warning,

        /// <summary>
        /// Info log type.
        /// </summary>
        Info,

        /// <summary>
        /// Debug log type.
        /// </summary>
        Debug,

        /// <summary>
        /// All log type.
        /// </summary>
        All
    }

    /// <summary>
    /// Primary class responsbile for logging.  This class is a combination between a singleton
    /// and a regular class to allow for the developers to have more customability.
    /// One thing worth mentioning, the only thing that this system will not allow developers to
    /// customize is the use of consecutive integers for log levels starting at 0.  Developers are
    /// free to use however many levels they want, define them however they want, however... that is the
    /// one limitation I am comfortable placing on them.
    /// </summary>
    public class Logger
    {
        #region Static fields
        private static Logger logger;
        private static List<string> logLevelDescription = new List<string>();
        #endregion

        #region Fields
        private int levels;
        private LoggerCollection loggerHandler = new LoggerCollection();
        private LoggerHandler defaultHandler;
        private int max;
        #endregion

        #region Constructors
        /// <summary>
        /// Initializes static members of the Logger class.
        /// </summary>
        static Logger()
        {
            logLevelDescription.Add("V_CRITICAL");
            logLevelDescription.Add("V_ERROR");
            logLevelDescription.Add("V_WARN");
            logLevelDescription.Add("V_INFO");
            logLevelDescription.Add("V_DEBUG");
            logLevelDescription.Add("V_ALL");
        }

        /// <summary>
        /// Initializes a new instance of the Logger class.
        /// With this constructor the developer is responsible for defining what
        /// they want the logger to do (in the defaultHandler).
        /// </summary>
        /// <param name="defaultHandler">Reference to the default handler.</param>
        public Logger(LoggerHandler defaultHandler)
        {
            this.Init(defaultHandler);
        }

        /// <summary>
        /// Initializes a new instance of the Logger class.
        /// Opens up a standard to file logger with the specified number of log levels.
        /// </summary>
        /// <param name="fileName">Where to log.</param>
        public Logger(string fileName)
        {
            this.Init(new TextFileLogger(fileName));
        }

        /// <summary>
        /// Initializes a new instance of the Logger class.
        /// User specifies only the number of log levels they require.  They are still obligated
        /// (assuming they want the logger to do something) to add a handler.
        /// </summary>
        public Logger()
        {
            this.Init(null);
        }
        #endregion

        #region Properties
        /// <summary>
        /// Gets or sets the default handler.
        /// </summary>
        public LoggerHandler DefaultHandler
        {
            get { return this.defaultHandler; }
            set { this.defaultHandler = value; }
        }

        /// <summary>
        /// Gets or sets the maximum logging level (note: this is not the total number of levels, but rather
        /// the upper bound where an action will or won't take placed based on the log level)
        /// </summary>
        public int MaximumLogLevel
        {
            get { return this.max; }
            set { this.max = value; }
        }

        /// <summary>
        /// Gets the LoggerCollection.
        /// </summary>
        protected LoggerCollection LoggerHandler
        {
            get { return this.loggerHandler; }
        }

        /// <summary>
        /// Gets or sets the maximum number of levels.
        /// </summary>
        protected int Max
        {
            get { return this.max; }
            set { this.max = value; }
        }

        /// <summary>
        /// Gets or sets the number of levels.
        /// </summary>
        protected int Levels
        {
            get { return this.levels; }
            set { this.levels = value; }
        }
        #endregion

        #region Static methods
        /// <summary>
        /// The singleton can get set in two ways:
        /// 1.) The developer promotes their class to be the Logger object inside the singleton
        /// 2.) We decide for them what their class is going to look like
        /// </summary>
        /// <returns>Returns Logger instance.</returns>
        public static Logger Singleton()
        {
            if (logger == null)
            {
                // use defaults
                string baseDirectory = AppDomain.CurrentDomain.BaseDirectory;

                // string location = Assembly.GetExecutingAssembly().Location;
                // string dir = Path.GetDirectoryName(baseDirectory);
                string logFile = Path.Combine(baseDirectory, DateTime.Now.ToShortDateString().Replace(@"/", @"-").Replace(@"\", @"-") + ".log");
                logger = new Logger(logFile);
            }

            return logger;
        }
        #endregion

        #region Public methods
        /// <summary>
        /// Takes the current object and places it as the internal singleton reference
        /// </summary>
        /// <returns>Returns reference to this.</returns>
        public Logger PromoteToStatic()
        {
            logger = this;
            return logger;
        }

        /// <summary>
        /// Adds a customized log handler to each log level
        /// </summary>
        /// <param name="handler">LoggerHandler instance.</param>
        public void AddSpecialLoggerToAllLevels(LoggerHandler handler)
        {
            if (handler == null)
            {
                return;
            }

            for (int level = 0; level < this.levels; level++)
            {
                this.AddSpecialLogger(level, handler);
            }
        }

        /// <summary>
        /// Adds a customized logger handler (e.g. log to file) to a specific level.
        /// Note: You can have (n log handlers assuming your system has the resources)
        /// </summary>
        /// <param name="level">At which level to add the LoggerHandler.</param>
        /// <param name="handler">LoggerHandler instance.</param>
        public void AddSpecialLogger(int level, LoggerHandler handler)
        {
            if (level < this.levels)
            {
                if (this.loggerHandler[level] != null)
                {
                    this.loggerHandler[level].Add(handler);
                }
                else
                {
                    this.loggerHandler[level] = new LevelHanderCollection();
                    this.loggerHandler[level].Add(handler);
                }
            }
        }

        /// <summary>
        /// Sugared method to add a simple file handler method
        /// </summary>
        /// <param name="level">At which level to add the logger.</param>
        /// <param name="fileName">Where to log.</param>
        public void AddSpecialLogger(int level, string fileName)
        {
            this.AddSpecialLogger(level, new TextFileLogger(fileName));
        }

        /// <summary>
        /// Invokes all appropriate log event handlers with the message
        /// </summary>
        /// <param name="level">At which level to log.</param>
        /// <param name="tag">Tag to log.</param>
        /// <param name="message">Message to log.</param>
        public void Log(LoggerLevels level, string tag, string message)
        {
            int level_ = (int)level;
            if ((level_ <= this.max) && (level_ < this.levels) && (this.loggerHandler[level_] != null))
            {
                foreach (LoggerHandler handler in this.loggerHandler[level_])
                {
                    if (logLevelDescription == null)
                    {
                        handler.Log(tag, level_, String.Empty, message);
                    }
                    else
                    {
                        handler.Log(tag, level_, logLevelDescription[level_], message);
                    }
                }
            }
        }

        /// <summary>
        /// Invokes the shutdown method for all log handlers
        /// </summary>
        public void Shutdown()
        {
            foreach (LevelHanderCollection handlerList in this.loggerHandler)
            {
                foreach (LoggerHandler handler in handlerList)
                {
                    handler.Shutdown();
                }
            }
        }
        #endregion

        #region Private methods
        /// <summary>
        /// Effectively the constructor (so no code would have to be repeated).  Consequently
        /// if one were to try to put this block inside the constructor matching the signature and
        /// then referenced it with :this(levels, defaultHandler) in the other constructors MS
        /// has a bit of a fit.  Dunno...this works, don't really care.
        /// </summary>
        /// <param name="handler">LoggerHandler instance.</param>
        private void Init(LoggerHandler handler)
        {
            this.levels = logLevelDescription.Count;
            this.defaultHandler = handler;
            this.max = this.levels - 1;

            LevelHanderCollection handler_ = new LevelHanderCollection();

            handler_.Add(handler);

            for (int i = 0; i < this.levels; i++)
            {
                this.loggerHandler.Add(handler_);
            }
        }
        #endregion

        #region Nested types
        /// <summary>
        /// LevelHandlerCollection class.
        /// </summary>
        protected class LevelHanderCollection : List<LoggerHandler>
        {
        }

        /// <summary>
        /// LoggerCollection class.
        /// </summary>
        protected class LoggerCollection : List<LevelHanderCollection>
        {
        }
        #endregion
    }
}